<template>
  <div>
    <h1>拼团活动列表</h1>
    <!-- 条件查询 -->
    <div style="margin-top: 10px">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="时间区间">
          <el-date-picker
            v-model="searchForm.beginTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="请选择开始时间"
            clearable
          />
          <span>-</span>
          <el-date-picker
            v-model="searchForm.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="请选择截止时间"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadGroupJoinList">查询</el-button>
          <el-button type="primary" @click="toAddGroupJoin">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格数据 -->
    <div style="margin-top: 10px">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="joinId" label="id" width="50" />
        <el-table-column prop="activeName" label="活动名称" width="120" />
        <el-table-column prop="joinName" label="商家团名称" width="160" />
        <el-table-column prop="joinDesc" label="拼团活动简介" width="140" />
        <el-table-column prop="unitName" label="商品单位" width="80" />
        <el-table-column prop="joinImageList" label="商品轮播图" width="130">
          <template #default="scope">
            <el-image
              v-for="item in scope.row.joinImageList"
              :src="item"
              :key="item"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="beginTime" label="活动开始时间" width="160" />
        <el-table-column prop="endTime" label="活动截止时间" width="160" />
        <el-table-column
          prop="expireTime"
          label="拼团时效（小时）"
          width="140"
        />
        <el-table-column prop="groupNum" label="拼团人数" width="80" />
        <el-table-column prop="buyMax" label="总购买数量限制" width="140" />
        <el-table-column prop="virtualNum" label="补齐人数" width="80" />
        <el-table-column prop="prodName" label="拼团商品" width="140" />
        <el-table-column prop="kindName" label="配送方式" width="80" />
        <el-table-column prop="payName" label="运费设置" width="80" />
        <el-table-column prop="sendMoney" label="运费" width="80" />
        <el-table-column prop="joinTop" label="排序" width="80" />
        <el-table-column prop="statusName" label="排序" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />

        <el-table-column label=" 操作">
          <template #default="scope">
            <el-button type="primary" @click="onJoin(scope.row)" size="small"
              >参团</el-button
            >
            <el-button type="success" @click="onCreate(scope.row)" size="small"
              >开团</el-button
            >
            <el-button type="info" @click="onUpdateJoin(scope.row)" size="small"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="onDeleteJoin(scope.row)"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 10px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加/修改 商家拼团活动---对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form :model="form">
          <el-form-item label="活动名称" :label-width="formLabelWidth">
            <el-select v-model="form.activeId" placeholder="请选择拼团活动">
              <el-option
                v-for="item in groupActiveList"
                :label="item.activeName"
                :value="item.activeId"
                :key="item.activeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商家活动名称" :label-width="formLabelWidth">
            <el-input v-model="form.joinName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商家活动简介" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              v-model="form.joinDesc"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="商品单位" :label-width="formLabelWidth">
            <el-select v-model="form.prodUnit" placeholder="请选择商品单位">
              <el-option
                v-for="item in unitList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/prod/type/uploadImage"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="活动开始时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.beginTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="请选择活动开始时间"
            />
          </el-form-item>
          <el-form-item label="活动截止时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.endTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="请选择活动截止时间"
            />
          </el-form-item>
          <el-form-item label="拼团时效（小时）" :label-width="formLabelWidth">
            <el-input-number v-model="form.expireTime" autocomplete="off" />
          </el-form-item>
          <el-form-item label="拼团人数" :label-width="formLabelWidth">
            <el-input-number v-model="form.groupNum" autocomplete="off" />
          </el-form-item>
          <el-form-item label="总购买数量限制" :label-width="formLabelWidth">
            <el-input-number v-model="form.buyMax" autocomplete="off" />
          </el-form-item>
          <el-form-item label="补齐人数" :label-width="formLabelWidth">
            <el-input-number v-model="form.virtualNum" autocomplete="off" />
          </el-form-item>
          <el-form-item label="拼团商品" :label-width="formLabelWidth">
            <el-select v-model="form.prodInfoId" placeholder="请选择拼团商品">
              <el-option
                v-for="item in prodInfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="配送方式" :label-width="formLabelWidth">
            <el-select v-model="form.sendKind" placeholder="请选择配送方式 ">
              <el-option
                v-for="item in kindList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="运费设置" :label-width="formLabelWidth">
            <el-select v-model="form.sendPay" placeholder="请选择运费设置">
              <el-option
                v-for="item in payList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="运费" :label-width="formLabelWidth">
            <el-input
              v-model="form.sendMoney"
              autocomplete="off"
              :disabled="form.sendPay != 2"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              v-if="title == '添加商家拼团活动'"
              @click="onSumbitAdd"
            >
              提交
            </el-button>
            <el-button
              type="primary"
              v-if="title == '修改商家拼团活动'"
              @click="onSumbitUpdate"
            >
              完成
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getGroupJoinPage,
  addGroupJoin,
  updateGroupJoin,
  deleteGroupJoin,
  getGroupActivePage,
  getDictList,
  getProdInfoPage,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps, UploadUserFile } from "element-plus";

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
  beginTime: "",
  endTime: "",
});

const title = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
  activeId: null,
  beginTime: "",
  buyMax: 0,
  joinImages: "",
  endTime: "",
  expireTime: 0,
  groupNum: 0,
  joinDesc: "",
  joinName: "",
  joinTop: 0,
  prodInfoId: null,
  prodUnit: null,
  sendKind: null,
  sendMoney: 0,
  sendPay: null,
  virtualNum: 0,
  joinImageList: [],
});

//参团/开团
const onJoin = (row: any) => {
  console.log("onJoin", row);
};

//上传多图片
const fileList = ref<UploadUserFile[]>([]);
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
//下拉框数据列表
const groupActiveList = ref([]);
const unitList = ref([]);
const prodInfoList = ref([]);
const kindList = ref([]);
const payList = ref([]);

//删除商家拼团活动
const onDeleteJoin = (row: any) => {
  console.log("onDeleteJoin", row);

  ElMessageBox.confirm("删除之后无法恢复，您确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      deleteGroupJoin(row.joinId).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadGroupJoinList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//显示修改商家拼团活动对话框
const onUpdateJoin = (row: any) => {
  title.value = "修改商家拼团活动";
  fileList.value = [];
  Object.assign(form.value, row);
  form.value.joinImageList.forEach((item) => {
    let img = {};
    img.url = item;
    fileList.value.push(img);
  });
  dialogFormVisible.value = true;
};

//确认修改
const onSumbitUpdate = () => {
  console.log("onSumbitUpdate");
  const imagess = [];
  fileList.value.forEach((item) => {
    if (item.response == undefined) {
      imagess.push(item.url);
    } else {
      imagess.push(item.response.data);
    }
  });
  form.value.joinImageList = imagess;
  updateGroupJoin(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      loadGroupJoinList();
      dialogFormVisible.value = false;
      fileList.value = [];
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//显示添加商家拼团活动对话框
const toAddGroupJoin = () => {
  title.value = "添加商家拼团活动";
  form.value = {
    activeId: null,
    beginTime: "",
    buyMax: 0,
    joinImages: "",
    endTime: "",
    expireTime: 0,
    groupNum: 0,
    joinDesc: "",
    joinName: "",
    joinTop: 0,
    prodInfoId: null,
    prodUnit: null,
    sendKind: null,
    sendMoney: 0,
    sendPay: null,
    virtualNum: 0,
    joinImageList: [],
  };
  fileList.value = [];
  dialogFormVisible.value = true;
};

//确认添加
const onSumbitAdd = () => {
  console.log("onSumbitAdd");
  const imageList = [];
  fileList.value.forEach((item) => {
    imageList.push(item.response.data);
  });
  form.value.joinImageList = imageList;
  addGroupJoin(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadGroupJoinList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadGroupJoinList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadGroupJoinList();
};

const loadGroupJoinList = () => {
  getGroupJoinPage(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadGroupJoinList();
  //获取拼团活动列表
  getGroupActivePage({ pageNum: 1, pageSize: 99999 }).then((res) => {
    if (res.data.code == 200) {
      groupActiveList.value = res.data.data.records;
    }
  });
  //商品单位列表
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  //拼团商品信息列表
  getProdInfoPage({ pageNum: 1, pageSize: 99999 }).then((res) => {
    if (res.data.code == 200) {
      prodInfoList.value = res.data.data.records;
    }
  });
  //商品单位列表
  getDictList(16).then((res) => {
    if (res.data.code == 200) {
      kindList.value = res.data.data;
    }
  });
  //商品单位列表
  getDictList(17).then((res) => {
    if (res.data.code == 200) {
      payList.value = res.data.data;
    }
  });
});
</script>

<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 条件搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
<!-- 上传图片样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
